<template>
  <div class="info">
    <van-cell-group>
      <van-field v-model="info.contactNumber" label="手机号" readonly placeholder="请输入手机号" />
    </van-cell-group>
    <van-cell-group>
      <van-field v-model="info.nickName" label="昵称" placeholder="请输入昵称" />
    </van-cell-group>
    <van-cell-group>
      <van-field label="头像" placeholder="请输入昵称">
        <template #input>
          <van-uploader v-model="userAvatarUrl" :max-count="1" :after-read="afterRead" />
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn">
      <van-button type="primary" @click="save">保存</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { queryUserInfo,updateUserInfo } from "@/api/index"
import { uploadFile } from '../../api';
import { showToast } from 'vant';
import useUserStore from '../../store/modules/user';
let host = import.meta.env.VITE_APP_BASE_API;
let info = ref({})
let userAvatarUrl = ref([])
let url = ''
function getInfo() {
  queryUserInfo().then(res => {
    info.value = res.data
    if(res.data.userAvatarUrl){
      userAvatarUrl.value = [
      { url: host + res.data.userAvatarUrl },
    ]
    }
   
  })
}
getInfo()

function afterRead(file) {
  console.log(file)
  const formData = new FormData();
  formData.append('file', file.file);
  uploadFile(formData).then(res => {
    url = res.fileName
    userAvatarUrl.value = [
      { url: host + res.fileName },
    ]
  })
}
// 保存
function save(){
  info.value.userAvatarUrl = url
  updateUserInfo(info.value).then(res=>{
    showToast('修改成功')
    useUserStore().getUserInfo()
  })
}
</script>

<style scoped lang="scss">
.btn {
  position: fixed;
  bottom: 180px;
  text-align: center;
  width: 100%;

  :deep(.van-button) {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    position: absolute;
    width: 200px;
    transform: translateX(-50%);
    left: 50%;
  }
}
</style>